package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.config.NacosRuleConstants;
import com.alibaba.csp.sentinel.dashboard.domain.cluster.ClusterGroupEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * packageName com.alibaba.csp.sentinel.dashboard.rule.nacos.ClusterMapNacosProvider
 *
 * @author liudonghai
 * @version JDK 11
 * @date 2025/8/1
 * @description TODO
 */
@Component("clusterMapNacosProvider")
public class ClusterMapNacosProvider implements DynamicRuleProvider<Set<ClusterGroupEntity>> {

    @Autowired
    private ConfigService configService;

    @Autowired
    private Converter<String, Set<ClusterGroupEntity>> converter;

    @Override
    public Set<ClusterGroupEntity> getRules(String appName) throws Exception {
        String rules = configService.getConfig(
                appName + NacosRuleConstants.CLUSTER_MAP_DATA_ID_POSTFIX,
                NacosRuleConstants.GROUP_ID,
                3000);

        if (StringUtil.isEmpty(rules)) {
            return new HashSet<>();
        }

        return converter.convert(rules);
    }
}

